import React, { useState } from 'react';
import { Input, InputNumber, Switch, Tag, Space, Button } from 'antd';
import { Icon } from '@iconify/react';
import { SafetyOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { CrudPage, DictionarySelect } from '@/components';
import type { SearchFormItem, ModalFormItem } from '@/components';
import * as planApi from './api';
import type { Plan } from '@/types';
import type { GetPlansParams } from './type';
import { useAuthStore } from '@/stores/useAuthStore';
import { useDictionary } from '@/hooks';
import PermissionModal from './modules/PermissionModal';

const PlanManagement: React.FC = () => {
  const { hasPermission } = useAuthStore();
  const { getLabel: getBillingCycleLabel } = useDictionary({ code: 'billing_cycle' });
  const { getLabel: getSupportLevelLabel } = useDictionary({ code: 'support_level' });
  
  // 权限配置弹窗状态
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState<Plan | null>(null);

  // 表格配置
  const columns: ColumnsType<Plan> = [
    {
      title: '套餐名称',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      fixed: 'left',
    },
    {
      title: '套餐代码',
      dataIndex: 'code',
      key: 'code',
      width: 100,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
      ellipsis: true,
    },
    {
      title: '月付价格',
      dataIndex: 'priceMonthly',
      key: 'priceMonthly',
      width: 100,
      align: 'right',
      render: (price: any) => {
        const priceNum = typeof price === 'string' ? parseFloat(price) : price;
        return `¥${priceNum.toFixed(2)}`;
      },
    },
    {
      title: '年付价格',
      dataIndex: 'priceYearly',
      key: 'priceYearly',
      width: 100,
      align: 'right',
      render: (price: any) => {
        const priceNum = typeof price === 'string' ? parseFloat(price) : price;
        return `¥${priceNum.toFixed(2)}`;
      },
    },
    {
      title: '资源限制',
      key: 'limits',
      width: 200,
      render: (_, record: Plan) => (
        <Space direction="vertical" size="small">
          <div>
            <Icon icon="mdi:account-multiple" style={{ marginRight: '4px' }} />
            用户：{record.maxUsers || '∞'}
          </div>
          <div>
            <Icon icon="mdi:folder" style={{ marginRight: '4px' }} />
            项目：{record.maxProjects || '∞'}
          </div>
          <div>
            <Icon icon="mdi:database" style={{ marginRight: '4px' }} />
            存储：{record.maxStorage ? `${(record.maxStorage / (1024 * 1024 * 1024)).toFixed(0)}GB` : '∞'}
          </div>
        </Space>
      ),
    },
    {
      title: '支持级别',
      dataIndex: 'supportLevel',
      key: 'supportLevel',
      width: 100,
      render: (level: string) => {
        const colorMap: Record<string, string> = {
          basic: 'default',
          priority: 'blue',
          dedicated: 'purple',
        };
        return <Tag color={colorMap[level] || 'default'}>{getSupportLevelLabel(level)}</Tag>;
      },
    },
    {
      title: '高级功能',
      key: 'features',
      width: 180,
      render: (_, record: Plan) => (
        <Space size="small" wrap>
          {record.hasApiAccess && <Tag color="blue">API</Tag>}
          {record.hasCustomDomain && <Tag color="green">自定义域名</Tag>}
          {record.hasSso && <Tag color="purple">SSO</Tag>}
          {record.hasWhiteLabel && <Tag color="orange">白标</Tag>}
          {record.hasAdvancedAnalytics && <Tag color="cyan">高级分析</Tag>}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 80,
      fixed: 'right',
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'success' : 'default'}>
          {isActive ? '启用' : '禁用'}
        </Tag>
      ),
    },
  ];

  // 搜索配置
  const searchItems: SearchFormItem[] = [
    {
      name: 'name',
      label: '套餐名称',
      component: <Input placeholder="请输入套餐名称" allowClear />,
      col: 6,
    },
    {
      name: 'supportLevel',
      label: '支持级别',
      component: <DictionarySelect code="support_level" placeholder="请选择支持级别" allowClear />,
      col: 6,
    },
  ];

  // 表单配置
  const formItems: ModalFormItem[] = [
    {
      name: 'name',
      label: '套餐名称',
      component: <Input placeholder="请输入套餐名称" />,
      rules: [{ required: true, message: '请输入套餐名称' }],
    },
    {
      name: 'code',
      label: '套餐代码',
      component: <Input placeholder="请输入套餐代码，如：basic" />,
      rules: [{ required: true, message: '请输入套餐代码' }],
    },
    {
      name: 'description',
      label: '套餐描述',
      component: <Input.TextArea placeholder="请输入套餐描述" rows={3} />,
    },
    {
      name: 'priceMonthly',
      label: '月付价格',
      component: <InputNumber min={0} precision={2} style={{ width: '100%' }} placeholder="请输入月付价格" addonBefore="¥" />,
      rules: [{ required: true, message: '请输入月付价格' }],
    },
    {
      name: 'priceYearly',
      label: '年付价格',
      component: <InputNumber min={0} precision={2} style={{ width: '100%' }} placeholder="请输入年付价格" addonBefore="¥" />,
      rules: [{ required: true, message: '请输入年付价格' }],
    },
    {
      name: 'maxUsers',
      label: '最大用户数',
      component: <InputNumber min={1} style={{ width: '100%' }} placeholder="留空表示无限制" />,
    },
    {
      name: 'maxProjects',
      label: '最大项目数',
      component: <InputNumber min={1} style={{ width: '100%' }} placeholder="留空表示无限制" />,
    },
    {
      name: 'maxStorage',
      label: '最大存储空间(字节)',
      component: <InputNumber min={0} style={{ width: '100%' }} placeholder="留空表示无限制，1GB=1073741824字节" />,
    },
    {
      name: 'supportLevel',
      label: '支持级别',
      component: <DictionarySelect code="support_level" placeholder="请选择支持级别" />,
      rules: [{ required: true, message: '请选择支持级别' }],
      initialValue: 'basic',
    },
    {
      name: 'hasApiAccess',
      label: 'API 访问权限',
      component: <Switch checkedChildren="支持" unCheckedChildren="不支持" />,
      valuePropName: 'checked',
      initialValue: false,
    },
    {
      name: 'hasCustomDomain',
      label: '自定义域名',
      component: <Switch checkedChildren="支持" unCheckedChildren="不支持" />,
      valuePropName: 'checked',
      initialValue: false,
    },
    {
      name: 'hasSso',
      label: '单点登录 (SSO)',
      component: <Switch checkedChildren="支持" unCheckedChildren="不支持" />,
      valuePropName: 'checked',
      initialValue: false,
    },
    {
      name: 'hasWhiteLabel',
      label: '白标功能',
      component: <Switch checkedChildren="支持" unCheckedChildren="不支持" />,
      valuePropName: 'checked',
      initialValue: false,
    },
    {
      name: 'hasAdvancedAnalytics',
      label: '高级分析',
      component: <Switch checkedChildren="支持" unCheckedChildren="不支持" />,
      valuePropName: 'checked',
      initialValue: false,
    },
    {
      name: 'isActive',
      label: '状态',
      component: <Switch checkedChildren="启用" unCheckedChildren="禁用" />,
      valuePropName: 'checked',
      initialValue: true,
    },
  ];

  // 打开权限配置弹窗
  const handleConfigPermission = (record: Plan) => {
    setSelectedPlan(record);
    setPermissionModalVisible(true);
  };

  return (
    <CrudPage<Plan, GetPlansParams>
      title="套餐管理"
      fetchApi={planApi.getPlans}
      createApi={planApi.createPlan}
      updateApi={planApi.updatePlan}
      deleteApi={planApi.deletePlan}
      columns={columns}
      searchItems={searchItems}
      formItems={formItems}
      formTitle={{ create: '新增套餐', edit: '编辑套餐' }}
      permissions={{
        create: hasPermission('plan:create'),
        update: hasPermission('plan:update'),
        delete: hasPermission('plan:delete'),
      }}
      scroll={{ x: 1400 }}
      formWidth={700}
      renderExtraActions={(record) => (
        <Button
          type="link"
          icon={<SafetyOutlined />}
          onClick={() => handleConfigPermission(record)}
          disabled={!hasPermission('plan:update')}
        >
          配置权限
        </Button>
      )}
    >
      {() => (
        <>
          {selectedPlan && (
            <PermissionModal
              visible={permissionModalVisible}
              planId={selectedPlan.id}
              planName={selectedPlan.name}
              onClose={() => {
                setPermissionModalVisible(false);
                setSelectedPlan(null);
              }}
            />
          )}
        </>
      )}
    </CrudPage>
  );
};

export default PlanManagement;
